<template>
  <div>
    <!-- Header 区域 -->
    <div class="header">
      <!-- 左侧：Logo 和标题 -->
      <div class="header-left">
        <h1>智慧校园统一身份验证平台</h1>
      </div>

      <!-- 右侧：用户头像和用户名下拉菜单 -->
      <div class="header-right">
        <el-dropdown trigger="click" @command="handleCommand">
          <template #default>
            <span class="user-info">
              <img class="avatar" :src="user.avatar" alt="Avatar" />
              <span class="username">{{ user.username }}</span>
            </span>
          </template>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="profile">个人主页</el-dropdown-item>
              <el-dropdown-item command="logout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import infoImgUrl1 from '../assets/img/student.jpg'

// 用户信息，初始状态从 localStorage 获取（若存在）
const user = reactive({
  loggedIn: false,
  username: '',
  avatar: infoImgUrl1
})

const router = useRouter()

// 下拉菜单命令处理
const handleCommand = (command) => {
  if (command === 'profile') {
    router.push('/profile')
  } else if (command === 'logout') {
    user.loggedIn = false
    user.username = ''
    user.avatar = infoImgUrl1
    localStorage.removeItem('user')
    localStorage.removeItem('token')  // 清除 token
    ElMessage.success('已退出登录')
    router.push('/login')  // 跳转到登录页
  }
}

// 页面加载时检查本地是否已有用户信息
onMounted(() => {
  const storedUser = localStorage.getItem('user')
  if (storedUser) {
    const parsedUser = JSON.parse(storedUser)
    if (parsedUser && parsedUser.loggedIn) {
      user.loggedIn = true
      user.username = parsedUser.username
      // 保持头像固定
      user.avatar = infoImgUrl1
    }
  }
})
</script>

<style scoped>
/* 整体字体设置 */
* {
  font-family: "微软雅黑", sans-serif;
}

/* Header整体样式（采用若依管理系统常见的深色风格） */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 30px;
  height: 60px;
  background-color: #2f4056;
  color: #fff;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

/* 左侧：Logo 和标题 */
.header-left {
  display: flex;
  align-items: center;
}
.header-left .logo {
  height: 40px;
  width: auto;
  margin-right: 10px;
}
.header-left h1 {
  font-size: 20px;
  margin: 0;
  color: #fff;
}

/* 右侧：用户头像和用户名下拉菜单 */
.header-right {
  display: flex;
  align-items: center;
}

/* 用户信息（头像和用户名） */
.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
}
.user-info .avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  margin-right: 8px;
  object-fit: cover;
}
.user-info .username {
  font-size: 16px;
  color: #fff;
}
</style>
